<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT">










<meta name="description" content="分布式系统中，一致性一直是一个比较重要的话题，分布式经典的CAP理论指出，任何一个分布式系统都无法同时满足一致性（Consistency)、可用性（Availablity）和分区容错性（Partition tolerance），最多只能满足两项，这里我们讨论如何使用分布式锁来满足一致性。">
<meta property="og:type" content="article">
<meta property="og:title" content="分布式锁以及三种实现方式">
<meta property="og:url" content="http://luqilinok.github.io/2019/07/17/distributedsystemlock/index.html">
<meta property="og:site_name" content="Lu QiLin&#39;s Blog">
<meta property="og:description" content="分布式系统中，一致性一直是一个比较重要的话题，分布式经典的CAP理论指出，任何一个分布式系统都无法同时满足一致性（Consistency)、可用性（Availablity）和分区容错性（Partition tolerance），最多只能满足两项，这里我们讨论如何使用分布式锁来满足一致性。">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-07-17T06:13:09.007Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="分布式锁以及三种实现方式">
<meta name="twitter:description" content="分布式系统中，一致性一直是一个比较重要的话题，分布式经典的CAP理论指出，任何一个分布式系统都无法同时满足一致性（Consistency)、可用性（Availablity）和分区容错性（Partition tolerance），最多只能满足两项，这里我们讨论如何使用分布式锁来满足一致性。">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://luqilinok.github.io/2019/07/17/distributedsystemlock/">





  <title>分布式锁以及三种实现方式 | Lu QiLin's Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Lu QiLin's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-technology">
          <a href="/categories/Technology/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            Technology
          </a>
        </li>
      
        
        <li class="menu-item menu-item-notes">
          <a href="/categories/Notes/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            Notes
          </a>
        </li>
      
        
        <li class="menu-item menu-item-personal">
          <a href="/categories/Personal/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            Personal
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            About
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://luqilinok.github.io/2019/07/17/distributedsystemlock/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="LuQiLin">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Lu QiLin's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">分布式锁以及三种实现方式</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2019-07-17T13:55:04+08:00">
                2019-07-17
              </time>
            

            

            
          </span>
          
  <span class="post-updated">
    &nbsp; | &nbsp; 更新于
    <time itemprop="dateUpdated" datetime="2019-07-17T14:13:09+08:00" content="2019-07-17">
      2019-07-17
    </time>
  </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Notes/" itemprop="url" rel="index">
                    <span itemprop="name">Notes</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>分布式系统中，一致性一直是一个比较重要的话题，分布式经典的CAP理论指出，任何一个分布式系统都无法同时满足一致性（Consistency)、可用性（Availablity）和分区容错性（Partition tolerance），最多只能满足两项，这里我们讨论如何使用分布式锁来满足一致性。</p>
<a id="more"></a>
<hr>
<h1 id="分布式锁具备条件"><a href="#分布式锁具备条件" class="headerlink" title="分布式锁具备条件"></a>分布式锁具备条件</h1><p>在分析分布式锁的实现之间，先来了解一下分布式锁应该具备哪些条件：</p>
<blockquote>
<p>1、在分布式系统环境下，一个方法在同一时间只能被一个机器的一个线程执行；</p>
<p>2、高可用的获取锁与释放锁；</p>
<p>3、高性能的获取锁与释放锁；</p>
<p>4、具备可重入特性；</p>
<p>5、具备锁失效机制，防止死锁；</p>
<p>6、具备非阻塞锁特性，即没有获取到锁将直接返回获取锁失败。</p>
</blockquote>
<h1 id="分布式锁的三种实现方式"><a href="#分布式锁的三种实现方式" class="headerlink" title="分布式锁的三种实现方式"></a>分布式锁的三种实现方式</h1><ul>
<li>基于数据库实现分布式锁；</li>
<li>基于缓存（Redis等）实现分布式缓存；</li>
<li>基于Zookeeper实现分布式锁。</li>
</ul>
<hr>
<h2 id="基于数据库的实现方式"><a href="#基于数据库的实现方式" class="headerlink" title="基于数据库的实现方式"></a>基于数据库的实现方式</h2><p>基于数据库实现方式的核心思想是：在数据库中创建一个表，表中包含方法名等字段，并在方法名字段上创建唯一索引，想要执行某个方法，就使用这个方法名向表中插入数据，成功插入则获取锁，执行完成后删除对应的行数据释放锁。</p>
<ul>
<li>创建一个表</li>
</ul>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">DROP</span> <span class="keyword">TABLE</span> <span class="keyword">IF</span> <span class="keyword">EXISTS</span> <span class="string">`method_lock`</span>;</span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> <span class="string">`method_lock`</span> (</span><br><span class="line">    <span class="string">`id`</span> <span class="built_in">int</span>(<span class="number">11</span>) <span class="keyword">unsigned</span> <span class="keyword">NOT</span> <span class="literal">NULL</span> AUTO_INCREMENT,</span><br><span class="line">    <span class="string">`method_name`</span> <span class="built_in">varchar</span>(<span class="number">64</span>) <span class="keyword">NOT</span> <span class="literal">NULL</span>,</span><br><span class="line">    <span class="string">`desc`</span> <span class="built_in">varchar</span>(<span class="number">255</span>) <span class="keyword">NOT</span> <span class="literal">NULL</span>,</span><br><span class="line">    <span class="string">`update_time`</span> <span class="built_in">timestamp</span> <span class="keyword">NOT</span> <span class="literal">NULL</span> <span class="keyword">DEFAULT</span> <span class="keyword">CURRENT_TIMESTAMP</span> <span class="keyword">ON</span> <span class="keyword">UPDATE</span> <span class="keyword">CURRENT_TIMESTAMP</span>,</span><br><span class="line">    PRIMARY <span class="keyword">KEY</span>(<span class="string">`id`</span>),</span><br><span class="line">    <span class="keyword">UNIQUE</span> <span class="keyword">KEY</span> <span class="string">`uidx_method_name`</span> (<span class="string">`method_name`</span>) <span class="keyword">USING</span> BTREE</span><br><span class="line">) <span class="keyword">ENGINE</span> = <span class="keyword">InnoDB</span> AUTO_INCREMENT=<span class="number">3</span> <span class="keyword">DEFAULT</span> <span class="keyword">CHARSET</span>=utf8</span><br></pre></td></tr></table></figure>
<ul>
<li>获取锁，往表中插入数据</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">INSERT INTO method_lock(method_name, desc) VALUES(&apos;methodname&apos;, &apos;测试methodname&apos;);</span><br></pre></td></tr></table></figure>
<p>我们对method_name做了唯一性约束，当有多个请求同时提交到数据库时，数据库会保证只有一个才做可以成功，那么我们可以认为操作成功的那个县城获得该方法的锁，可以执行具体内容。</p>
<ul>
<li>释放锁，删除数据</li>
</ul>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">DELETE</span> <span class="keyword">FROM</span> method_lock <span class="keyword">WHERE</span> method=<span class="string">'methodname'</span>;</span><br></pre></td></tr></table></figure>
<p>注意：<br>1、因为是基于数据库实现的，数据库的可用性和性能将直接影响分布式锁的可用性及性能，所以，数据库需要双机部署、数据同步、主备切换；<br>2、不具备可重入的特性，因为同一个线程在释放锁之前，行数据一直存在，无法再次成功插入数据，所以，需要在表中新增一列，用于记录当前获取到锁的机器和线程信息，在再次获取锁的时候，先查询表中机器和线程信息是否和当前机器和线程相同，若相同则直接获取锁；<br>3、没有锁失效机制，因为有可能出现成功插入数据后，服务器宕机了，对应的数据没有被删除，当服务恢复后一直获取不到锁，所以，需要在表中新增一列，用于记录失效时间，并且需要有定时任务清除这些失效的数据；<br>4、不具备阻塞锁特性，获取不到锁直接返回失败，所以需要优化获取逻辑，循环多次去获取；<br>5、在实施的过程中会遇到各种不同的问题，为了解决这些问题，实现方式将会越来越复杂；依赖数据库需要一定的资源开销，性能问题需要考虑。</p>
<hr>
<h2 id="基于Redis的实现方式"><a href="#基于Redis的实现方式" class="headerlink" title="基于Redis的实现方式"></a>基于Redis的实现方式</h2><p>1.使用Redis的原因：</p>
<ul>
<li>Redis由很高的性能；</li>
<li>Redis本身的语义对锁的获取和释放有很好的支持</li>
</ul>
<p>2.Redis基本命令：</p>
<p>（1）SETNX</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">SETNX key val: 当且仅当key不存在时，set一个key为val的字符串，返回1；若key存在，则什么都不做，返回0。</span><br></pre></td></tr></table></figure>
<p>(2)expire</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">expire key timeout：为key设置一个超时时间，单位为second，超过这个时间锁会自动释放，避免死锁。</span><br></pre></td></tr></table></figure>
<p>(3)delete</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">delete key：删除key</span><br></pre></td></tr></table></figure>
<p>3.实现思想：</p>
<p>（1）获取锁的时候使用SETNX加锁，并使用expire命令为锁添加一个超时时间，超过该时间则自动释放该锁，锁的value值为随机生成的UUID，通过此在释放锁的时候进行判断；<br>（2）获取锁的时候还设置一个获取的超时时间，若超过这个时间则放弃获取锁；<br>（3）释放锁的时候，通过UUID判断是不是该锁，若是该锁，则执行delete进行锁释放。</p>
<hr>
<h2 id="基于Zookeeper的实现方式"><a href="#基于Zookeeper的实现方式" class="headerlink" title="基于Zookeeper的实现方式"></a>基于Zookeeper的实现方式</h2><p>ZooKeeper是一个为分布式应用提供一致性服务的开源组件，它内部是一个分层的文件系统目录树结构，规定同一个目录下只能有一个唯一文件名。基于ZooKeeper实现分布式锁的步骤如下：<br>（1）创建一个目录mylock；<br>（2）线程A想获取锁就在mylock目录下创建临时顺序节点；<br>（3）获取mylock目录下所有的子节点，然后获取比自己小的兄弟节点，如果不存在，则说明当前线程顺序号最小，获得锁；<br>（4）线程B获取所有节点，判断自己不是最小节点，设置监听比自己次小的节点；<br>（5）线程A处理完，删除自己的节点，线程B监听到变更事件，判断自己是不是最小的节点，如果是则获得锁。<br>优点：具备高可用、可重入、阻塞锁特性，可解决失效死锁问题。<br>缺点：因为需要频繁的创建和删除节点，性能上不如Redis方式。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/07/13/networksocket8/" rel="next" title="网络编程之UNIX域协议">
                <i class="fa fa-chevron-left"></i> 网络编程之UNIX域协议
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/07/17/kernel-5/" rel="prev" title="Linux系统之内核准备">
                Linux系统之内核准备 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">LuQiLin</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">80</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">1</span>
                  <span class="site-state-item-name">categories</span>
                
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#分布式锁具备条件"><span class="nav-number">1.</span> <span class="nav-text">分布式锁具备条件</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#分布式锁的三种实现方式"><span class="nav-number">2.</span> <span class="nav-text">分布式锁的三种实现方式</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#基于数据库的实现方式"><span class="nav-number">2.1.</span> <span class="nav-text">基于数据库的实现方式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#基于Redis的实现方式"><span class="nav-number">2.2.</span> <span class="nav-text">基于Redis的实现方式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#基于Zookeeper的实现方式"><span class="nav-number">2.3.</span> <span class="nav-text">基于Zookeeper的实现方式</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">LuQiLin</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
